package cn.ys.search.service.impl;

import cn.ys.base.util.*;
import cn.ys.org.domain.Shop;
import cn.ys.org.mapper.ShopMapper;
import cn.ys.search.domain.SearchMasterMsg;
import cn.ys.search.domain.SearchMasterMsgAuditLog;
import cn.ys.search.dto.SearchMasterMsgDto;
import cn.ys.search.mapper.SearchMasterMsgAuditLogMapper;
import cn.ys.search.service.ISearchMasterMsgService;
import cn.ys.base.service.impl.BaseServiceImpl;
import cn.ys.user.domain.Logininfo;
import cn.ys.user.domain.User;
import cn.ys.user.mapper.LogininfoMapper;
import cn.ys.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ys
 * @since 2023-01-10
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper logMapper;

    @Autowired
    private ShopMapper shopMapper;

    // 寻主信息发布
    @Override
    public AjaxResult publish(SearchMasterMsgDto dto) {
        // 1.参数校验
        // 2.保存信息
        SearchMasterMsg msg = new SearchMasterMsg();
        BeanUtils.copyProperties(dto,msg);
        // 2.3设置状态
        msg.setState(0);
        // 2.2设置userId
        Logininfo logininfo = LoginContext.getUserInfo().getLogininfo();
        User user = logininfoMapper.findByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        super.add(msg);
        // 3.信息审核 百度AI审核
        if(!BaiduAuditUtils.TextCensor(dto.getName())){
            // 3.2审核不通过 添加日志
            SearchMasterMsgAuditLog msgAuditLog = new SearchMasterMsgAuditLog();
            msgAuditLog.setAuditTime(new Date());
            msgAuditLog.setNote("存在违法字符" + dto.getName());
            msgAuditLog.setMsgId(msg.getId());
            msgAuditLog.setState(0);
            msgAuditLog.setAuditId(-1L);
            // 3.3添加审核日志
            logMapper.add(msgAuditLog);
            // 更改状态审核失败
            msg.setState(2);
        }else {
            // 3.2审核通过 分配店铺
            // 获取发布人地址
            Point point = DistanceUtil.getPoint(dto.getAddress());
            // 匹配合适店铺
            List<Shop> shopList = shopMapper.findAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopList);
            // 将宠物归属到相应的店铺
            if(nearestShop != null){
                msg.setShopId(nearestShop.getId());
            }
            // 修改审核状态
            msg.setState(1);
        }
        // 4.更新店铺
        super.update(msg);
        return AjaxResult.me().success();
    }
}
